package com.fudan.adse.component;

import com.alibaba.fastjson.JSON;
import com.fudan.adse.domain.cont.AuthConstant;
import com.fudan.adse.domain.po.*;
import com.fudan.adse.mbg.mapper.ResourceMapper;
import com.fudan.adse.mbg.mapper.RoleMapper;
import com.fudan.adse.mbg.mapper.RoleResourceMapper;
import com.fudan.adse.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.stream.Collectors;

/**
 * @author Jerry Zhang <zhangjian16@fudan.edu.cn>
 * @desc 资源与角色访问对应关系操作组件
 * @date 2022-11-09 00:35
 */
@Component
public class ResourceRoleRulesHolder {
    @Autowired
    private ResourceMapper resourceMapper;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private RoleResourceMapper roleResourceMapper;
    @Autowired
    private RedisService redisService;
    @Value("${spring.application.name}")
    private String applicationName;
    /**
     * 启动程序时初始化至 redis 中
     */
    @PostConstruct
    public void initResourceRolesMap(){
        Map<String, List<String>> resourceRoleMap = new TreeMap<>();
        List<Resource> resourceList = resourceMapper.selectByExample(new ResourceExample());
        List<Role> roleList = roleMapper.selectByExample(new RoleExample());
        List<RoleResource> relationList = roleResourceMapper.selectByExample(new RoleResourceExample());
        for (Resource resource : resourceList) {
            Set<Integer> roleIds = relationList.stream().filter(item -> item.getResourceId().equals(resource.getId())).map(RoleResource::getRoleId).collect(Collectors.toSet());
            List<String> roleNames = roleList.stream().filter(item -> roleIds.contains(item.getId())).map(item -> item.getId() + "_" + item.getRoleName()).collect(Collectors.toList());
            resourceRoleMap.put("/" + applicationName + resource.getUrl(), roleNames);
        }
        redisService.del(AuthConstant.RESOURCE_ROLES_MAP_KEY);
        redisService.set(AuthConstant.RESOURCE_ROLES_MAP_KEY, JSON.toJSONString(resourceRoleMap));
    }
}
